﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using MySqlConnector;

namespace _12通过数据库读取配置信息;

class Program
{
    static void Main(string[] args)
    {
        string connStr = "Server=localhost;database=localhosttestdb;userId=root;password=;port=3306";
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.AddDbConfiguration(() => new MySqlConnection(connStr), "T_Configs", true, TimeSpan.FromSeconds(2));
        ServiceCollection service = new ServiceCollection();
        IConfigurationRoot configRoot = cb.Build();
        service.AddOptions().Configure<Config>(config => configRoot.Bind(config));
        service.AddScoped<ConfigController>();
        service.AddScoped<Config>();
        using (var sp = service.BuildServiceProvider())
        {
            var myconfig = sp.GetRequiredService<ConfigController>();
            myconfig.Print();
        }
    }
}

class ConfigController
{
    private readonly IOptionsSnapshot<Config> opt;

    public ConfigController(IOptionsSnapshot<Config> opt)
    {
        this.opt = opt;
    }

    public void Print()
    {
        var config = opt.Value;
        Console.WriteLine(config.Print());
    }
}
class Config
{
    public string Name { get; set; } = "/";
    public string Age { get; set; } = "/";
    public Proxy myProxy { get; set; }

    public string Print()
    {
        return $"{Name},{Age},{myProxy.Print()}";
    }
}

class Proxy
{
    public string Service { get; set; }
    public int Port { get; set; }

    public string Print()
    {
        return $"{Service},{Port}";
    }
}